/**
 * Created by Lcp on 2018/3/14.
 */
var Photos = ['','','','',[]],
    PhotoNames = ['','','','',[]];

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
$('#mation').bootstrapValidator({
    message: '必填',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        username: {
            message: '',
            validators: {
                notEmpty: {
                    message: '请输入姓名'
                },
                stringLength: {
                    min: 2,
                    max: 5,
                    message: '姓名长度介于2-5'
                },
                regexp: {
                    regexp: /^[\u4e00-\u9fa5]*$/,
                    message: '请输入中文'
                }
            }
        },
        fileOne:{
            message:'',
            validators:{
                notEmpty:{
                    message: '请上传现场视频全屏截图'
                }
            }
        },
        fileTwo:{
            message:'',
            validators:{
                notEmpty:{
                    message: '请上传视频人脸截图（网上逃犯照片）'
                }
            }
        },
        fileThree:{
            message:'',
            validators:{
                notEmpty:{
                    message: '请上传比对结果全屏截图'
                }
            }
        },
        fileFour:{
            message:'',
            validators:{
                notEmpty:{
                    message: '请上传认定对象详情'
                }
            }
        },
        fileFive:{
            message:'',
            validators:{
                notEmpty:{
                    message: '请上传抓获时间截图'
                }
            }
        },
        card:{
            message: '',
            validators:{
                regexp:{
                    regexp: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    message: '请输入正确的身份证号'
                }
            }
        },
        peopleKind:{
            message:'',
            validators:{
                stringLength: {
                    min: 0,
                    max: 10,
                    message: '最多10个字符'
                },
                regexp:{
                    regexp: /^[\u4e00-\u9fa5]*$/,
                    message: '请输入中文'
                }
            }
        },
        newName: {
            message: '',
            validators: {
                stringLength: {
                    min: 2,
                    max: 5,
                    message: '姓名长度介于2-5'
                },
                regexp: {
                    regexp: /^[\u4e00-\u9fa5]*$/,
                    message: '请输入中文'
                }
            }
        },
        newCard:{
            message:'',
            validators:{
                regexp:{
                    regexp: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    message: '请输入正确的身份证号'
                }
            }
        },
        date:{
            message:'',
            validators:{
                date:{
                    format: 'YYYY-MM-DD',
                    message: '日期格式不正确'
                }
            }
        },
        number:{
            message:'',
            validators:{
                regexp:{
                    regexp: /^([1-9]{1})|([1-9]\d)$]/,
                    message: '请输入整数'
                }
            }
        },
        caseNum:{
            message:'',
            validators:{
                regexp:{
                    regexp: /^[A]{1}\d{22}$/,
                    message: '案件编号为A开始和22位数字组成'
                }
            }
        },
        caseKind:{
            message:'',
            validators:{
                stringLength: {
                    min: 0,
                    max: 10,
                    message: '最多10个字符'
                },
                regexp:{
                    regexp: /^[\u4e00-\u9fa5]*$/,
                    message: '请输入中文'
                }
            }
        },
        remark:{
            message:'',
            validators:{
                stringLength: {
                    min: 0,
                    max: 20,
                    message: '最多20个字符'
                }
            }
        }
    }
});
laydate.render({
    elem: '#date', //指定元素
    showBottom:false,
    max: 0
});
//图片上传
function fileImg(node,num){
    $('.newAppendImg').remove();
    if (node.value){
        for(var i = 0; i < node.files.length; i++){
            var file = null;
            (function (i){
                if(node.files && node.files[i] ){
                    file = node.files[i];
                }else if(node.files && node.files.item(i)) {
                    file = node.files.item(i);
                }
                var fileReader = new FileReader();
                //canvas实现图片处理预览上传
                fileReader.readAsDataURL(file);
                fileReader.onprogress = function(event){
                }
                fileReader.onload = function(event){
                    var result = event.target.result;   //返回的dataURL
                    var image = new Image();
                    image.src = result;
                    image.onload=function(){
                        if(i == 0){
                            $(node).parent().find('img').eq(0).attr('src',result);
                        }else{
                            $(node).before('<img src="'+ result +'" onerror="nofind(this)" class="baseImg newAppendImg">');
                        }
                        //昨天的时间
                        var today = new Date();
                        today.setDate(today.getDate());
                        var s1 = today.format("yyyy-MM-dd");
                        $(node).parent().find('input').css({height: $(node).parent().parent().height() + 'px'});
                        var str = $(node).parent().parent().find('label').html().substring(8,$(node).parent().parent().find('label').html().lastIndexOf('：')) + '-' + new Date().getTime();
                        if(num == 4){
                            Photos[num].push(result.substring(result.indexOf(',') + 1));
                            PhotoNames[num].push(`${faceImgAddress}${$.trim($('.username').val())}-${str}-${i}.png`);
                        }else{
                            Photos[num] = result.substring(result.indexOf(',') + 1);
                            PhotoNames[num] = `${faceImgAddress}${$.trim($('.username').val())}-${str}.png`;
                        }
                    }
                };
                fileReader.onerror = function( event) {
                    console.log('error')
                }
            })(i)
        }
    }else{
        $(node).parent().find('img').attr('src','fileImg/img/add.jpg');
        if(num == 4){
            Photos[num] = [];
            PhotoNames[num] = [];
        }else{
            Photos[num] = '';
            PhotoNames[num] = '';
        }
    }
}
//提交存储
function submitForm(item) {
    if($('.username').val() != '' && Photos[0] != '' && Photos[1] != '' && Photos[2] != '' && Photos[3] != '' && Photos[4].length != 0){
        $('button[type="submit"]').attr('disabled',true);
        var newPhotoNames = `${PhotoNames[0]}|${PhotoNames[1]}|${PhotoNames[2]}|${PhotoNames[3]}|${PhotoNames[4].join('|')}`.split('|'),
            newPhotos = `${Photos[0]}|${Photos[1]}|${Photos[2]}|${Photos[3]}|${Photos[4].join('|')}`.split('|');
        var formData = new FormData();
        formData.append('photos', newPhotos);
        formData.append('photoNames', newPhotoNames);
        $.ajax({
            type: 'post',
            url: uploadUrl + 'upload',
            contentType: false,
            processData: false,
            data: formData,
            async: false,
            beforeSend: function(){
                Loading();
            },
            success: function(response){
                closeLoading();
                var str = `${response.content.photos[4].wllj}`;
                if(response.content.photos.length > 5){
                    for(var i = 5; i < response.content.photos.length; i++){
                        str += `,${response.content.photos[i].wllj}`;
                    }
                }
                if(response.responseCode == '1000'){
                    $.ajax({
                        type: 'post',
                        url: baseUrls + 'faceResult',
                        data: {
                            name: $('.username').val(),
                            idcard: $('.card').val(),
                            type: $('.kind').val(),
                            personateName: $('.newName').val(),
                            personateIdcard: $('.newCard').val(),
                            capturedTime: $('.date').val(),
                            solveCaseNum: $('.number').val(),
                            caseNum: $('.caseNum').val(),
                            caseType: $('.caseKind').val(),
                            comments: $('.remark').val(),
                            screenPhotoFull: response.content.photos[0].wllj,
                            screenPhotoFace: response.content.photos[1].wllj,
                            comparePhotoFull: response.content.photos[2].wllj,
                            comparePhotoFace: response.content.photos[3].wllj,
                            capturedResultPhoto: str
                        },
                        async: false,
                        beforeSend: function () {
                            Loading();
                        },
                        success: function (response) {

                        },
                        error: function(){

                        }
                    })
                }
            },
            error: function(){
                closeLoading();
            }
        })
        window.location.reload();
    }else{
        return true;
    }
}